﻿<template>
    <div class="video-details-area">
        <div class="video-main">
            <video-player :options="playerOptions"></video-player>
        </div>
        <div class="detail-doc">
            <h3 class="doc-title" v-html="videoData['title']"></h3>
            <em class="doc-sub" v-html="videoData['subTitle']"></em>
            <div class="doc-main">
                <p v-html="videoData['content']"></p>
            </div>
            <div class="doc-play-msg">
                <i class="msg-icon" :style="'background-image: url(' + require('../../../assets/image/discover/b_01.png') + '); background-size: contain; width: 20px; height: 10px; display: inline-block; background-repeat: no-repeat; float: left; margin-top: 0.22rem;'"></i>
                <span class="play-count" v-if="videoData['view'] || videoData['view'] == 0">
                    {{(parseInt(videoData['pageViewDefault']) + parseInt(videoData.view))>10000 ? parseInt((parseInt(videoData['pageViewDefault']) + parseInt(videoData.view))/10000) : parseInt((parseInt(videoData['pageViewDefault']) + parseInt(videoData.view)))}}
                    <b v-show="(parseInt(videoData['pageViewDefault']) + parseInt(videoData.view))>10000" style="font-style: normal;">万</b>
                </span>
            </div>
            <span class="more-btn" @click="showDetails"><img class="detail-icon" :src="require('../../../assets/image/discover/details-icon.png')" /></span>
        </div>
        <div class="recommend" v-if="listMsg && (JSON.stringify(listMsg) !== '[]')">
            <div class="rec">相关推荐</div>
            <list-box :listbox="listMsg"></list-box>
            <div v-if="listMsg && listMsg.length > 1" class="last-end">~油门到底了~</div>
        </div>
    </div>
</template>

<script>
import common from "../../../assets/js/common.js";
import { videoPlayer } from 'vue-video-player';
import listBox from './../common/listbox';
import url from 'url';
import qs from 'querystring';
import Vue from 'vue';

require('videojs-resolution-switcher');

export default {
    data() {
        return {
            /**
             * 视频配置项
             */
            playerOptions: {
                /*source: [],
                language: 'zh-CN',
                autoplay: false,
                poster: '//i3.chexiangsit.com/msweb02/upload/resources/image/2017/03/02/34223.png', // 配置视频展示图
                defaultSrcReId: 2,
                height: 217*/
                
                plugins: {
                    videoJsResolutionSwitcher: {
                        ui: true,
                        default: 3,
                        dynamicLabel: true
                    }
                },
                language: 'zh-CN',
                autoplay: false,
//              playbackRates: [0.7, 1, 1.3, 1.5, 1.7],
                poster: "",
                height: 217,
                
                source: [] // 设置播放源
            },
            
            detailId: 0, // 视频id
            lifeType: 0, // 类目id
            videoData: [], // 视频信息
            
            listMsg: [],

            
            flog: true 

        }
    },
    components:{ listBox, videoPlayer },
//  data end 
    mounted() {
        var me = this;

        var tar = url.parse(window.location.href).query;
        var queryObj = qs.parse(tar);
        me.artColumn = queryObj['artColumn']; // 当前类目  
        me.artId = queryObj['artId']; // 视频id
        
        // 获得视频信息
        me.getVideo();
        // 推荐列表 
        me.recList();


        var myPlayer = videojs('vjs_video_3_html5_api');

        // me.myPlayer = myPlayer;

        // myPlayer.requestFullscreen();
       
        myPlayer.on("play",function () {
               myPlayer.requestFullscreen()
        });

        myPlayer.on("ended",
            function () {
                myPlayer.exitFullscreen();
        });


    },
    beforeDestroy(){
        //lb.closeWebview();
        window.location.reload();
    },
    destroyed(){  
        //lb.closeWebview();      
        window.location.reload();
    },
    methods: {
        playerStateChanged() {
            console.info(1111);
        },

        /**
         * 获取视频详情
         */
        getVideo: function() {
            var me = this;
            
            // 视频详情
            me.$http.get(common.isdev() + '/cxb/app/discover/discoveydetail/index.shtml', {}).then(function(d) {
                var data = me.parseData(d.body);
                if (data.errorCode == 0) {
                    var result = data.result.creditTradeVOs;
                    var resultLen = result.length;
                    var tmpData;
                    
                    while (resultLen--) {
                        // 匹配当前 id 的视频
                        if (result[resultLen]['id'] == me.artId) {
                            tmpData = result[resultLen];    
                        }
                    }
                    // 阅读量 & data
                    me.reading(tmpData);
                    // 增加浏览量
                    me.addReading(tmpData);
                }
            });
            
        },
        
        /**
         * 阅读量
         */
        reading: function(data) {
            var me = this;
            var milieuObj = {
                'prod':'chexiang',
                'pre':'chexiangpre',
                'sit':'chexiangsit',
                'development': 'chexiangpre' 
            }
            var host = '//cxjapp.'+milieuObj[process.env.NODE_ENV]+'.com';
            if (me.isEmptyObject(data)) {
                // 阅读量接口
                Vue.http({
                    url: host + '/service/discovery/getPageView/0.htm',
                    params: {"articleId": sessionStorage.getItem('id') || data['id']},
                    method: 'JSONP',
                    jsonp: 'jsonp'
                }).then(function (response){
                    var d = JSON.parse(response.bodyText);
                    if (d.errorCode == 0) {
                        // 处理浏览量
                        data['view'] = d.result;
                    }
                    
                    // 解析实体
                    if (data['content']) {
                        // 转换实体
                        data['content'] = me.HTMLDeCode(data['content']);
                        
                        // 设置 title
                        document.title = me.htmlDecodeByRegExp(data['title']);
                    } else {
                        data['content'] = '暂无内容';
                    }
                    
                    var vType = data['videoType'].split(',');
                    var vIcon = [];
                    for (var i=0; i<vType.length; i++) {
                        vIcon.push({});                        
                    }
                    
                    // 设置视频信息 【icon 和 src】
                    for (var t=0; t<vType.length; t++) {
                        switch (vType[t]){ // [1,原画] [2,高清] [3,超清]
                        	case '1':
                                    vIcon[t]['label'] = '原画'; 
                                    vIcon[t]['src'] = data['sourceOriginal'];
                                    vIcon[t]['type'] = 'video/mp4';
                                    vIcon[t]['res'] = 1;
                        		break;
                        	case '2':
                                    vIcon[t]['label'] = '高清';                        	    
                                    vIcon[t]['src'] = data['sourceDefinition'];
                                    vIcon[t]['type'] = 'video/mp4';
                                    vIcon[t]['res'] = 1;
                        		break;
                        	case '3':
                                    vIcon[t]['label'] = '超清';                        	    
                                    vIcon[t]['src'] = data['sourceSuper'];
                                    vIcon[t]['type'] = 'video/mp4';
                                    vIcon[t]['res'] = 1;
                        	    break;
                        }
                    }
                    // 设置视频主图
                    me.playerOptions.poster = data['image'];
                    // 设置视频信息
                    me.playerOptions.source = vIcon;
                    // 推荐列表
                    me.videoData = data;
                });
            } 
        },
        
        /**
         * 增加阅读量
         */
        addReading: function(data) {
            var me = this;
            var milieuObj = {
                'prod':'chexiang',
                'pre':'chexiangpre',
                'sit':'chexiangsit',
                'development': 'chexiangpre' 
            }
            var host = '//cxjapp.'+milieuObj[process.env.NODE_ENV]+'.com';
            if (me.isEmptyObject(data)) {
                // 阅读量接口
                Vue.http({
                    url: host + '/service/discovery/addPageView/0.htm',
                    params: {"articleId": sessionStorage.getItem('id') || data['id']},
                    method: 'JSONP',
                    jsonp: 'jsonp'
                }).then(function (response){
                    console.log('浏览量+1');                    
                });
            } 
        },
        
        /**
         * 推荐列表
         */
        recList: function() {
            var me = this;
            var listData = [];
            
            // 相同栏目
            me.$http.get(common.isdev() + '/cxb/app/discover/discoveydetail/index.shtml', {}).then(function(d) {
                var data = me.parseData(d.body);
                
                if (data.errorCode == 0) {
                    var len = data.result.creditTradeVOs.length;
                    var tmpData = data.result.creditTradeVOs;
                    
                    // 拼接url
                    while(len--) {
                        // type  [1,视频] [2, 文章] 
                        if (tmpData[len].type == 1) {
                            tmpData[len]['detailsUrl'] = common.path()+'/discover/videodetails/videodetails.'+common.isHtml()+'?artColumn=' + tmpData[len]['artColumn'] + '&artId=' + tmpData[len]['id'];
                        } else if(tmpData[len].type == 2) {
                            tmpData[len]['detailsUrl'] = common.path()+'/discover/imgdetsils/imgdetsils.'+common.isHtml()+'?artColumn=' + tmpData[len]['artColumn'] + '&artId=' + tmpData[len]['id'];
                        }
                    }
                    
                    // 获取 sessionStorage 中的 版本，平台，cityCode信息
                    var appVersion = sessionStorage.getItem('appVersion') || '3.6'; // 默认版本
                    var plateformType = sessionStorage.getItem('plateformType') || 'both'; // 默认平台 both android 和 ios 都可用 
                    var cityCode = sessionStorage.getItem('cityCode') || '310100'; // 城市code
                    
                    // 过滤版本&过滤系统
                    var listArr = [];
                    for (var i=0; i<tmpData.length; i++) {
                        if (tmpData[i]['appVersion'] != appVersion && (plateformType || tmpData[i]['plateformType'] == plateformType)) {
                            listArr.push(tmpData[i]);
                        }
                    }
                    var tmpListArr = [];
                    // 过滤当前栏目
                    for(var i=0; i<listArr.length; i++) {
                        if (listArr[i]['artColumn'] == me.artColumn) {
                            tmpListArr.push(listArr[i]);
                        }
                    }
                    
                    // 业务分类 分组   // map  {a: [{}, {}, {}], b: [{}] }
                    var objMap = {};
                    for(var i=0; i<tmpListArr.length; i++) { // bizCategory [业务分类]
                        var artColumns = tmpListArr[i]['artColumn'];
                        if (objMap[artColumns]) { // 判断`bizCategory` 的value 值 
                            objMap[artColumns].push(tmpListArr[i]); 
                        } else {
                            var _listArr = [];
                            _listArr.push(tmpListArr[i]); // [{}, {}, {}]
                            objMap[artColumns] = _listArr;
                        }
                    }
                    
                    // 分组  // 按 objMap key的value遍历   // [{}, {}, {}]
                    // 是否显示  和  是否当前城市  
                    var availableDetails = []; 
                    for(var j in objMap) {
                        if (objMap[j].length == 1 && objMap[j].isShow == 1) { // isShow （1【显示】 0【隐藏】）  
                            // 判断是否全国 
                            if (objMap[j]['generic'] == 1) { // generic （1【全国显示】 0【全国隐藏】）
                                availableDetails.push(objMap[j]);
                            } else if (objMap[j]['cityCode'] == cityCode) {
                                availableDetails.push(objMap[j]);                                
                            }
                        } else {
                            var tmp = objMap[j];  //  {a: [{}, {}, {}], b: [{}] }
                            for(var m=0; m<tmp.length; m++) {
                                // 解析城市code
                                var codeArr = tmp[m]['cityCode'].split(',');
                                for(var t=0; t<codeArr.length; t++) {
                                    if (tmp[m]['generic'] == 1) {
                                    // 全国
                                        availableDetails.push(tmp[m]);
                                        break;
                                    } else if (tmp[m].isShow == true && codeArr[t] == cityCode) {
                                    // 各个城市
                                        availableDetails.push(tmp[m]);
                                    }
                                }
                            }
                        }
                    }
                    
                    var info = [];
                    // 过滤当前id的详情
                    for (var t=0; t<availableDetails.length; t++) {
                        if (availableDetails[t]['id'] != me.artId){
                            info.push(availableDetails[t]);
                        }
                    }
                    // 读取阅读量
                    me.read(info);
               }
                
            });
            
        },
        
        /**
         * 阅读量
         */
        read: function(data) {
            var me = this;
            var milieuObj = {
                'prod':'chexiang',
                'pre':'chexiangpre',
                'sit':'chexiangsit',
                'development': 'chexiangpre' 
            }
            var host = '//cxjapp.'+milieuObj[process.env.NODE_ENV]+'.com';
            var len = data.length;
            var num = len;
            if (data) {
                // 阅读量接口
                for(var i=0; i<len; i++) {
                    (function(i) {
                        Vue.http({
                            url: host + '/service/discovery/getPageView/0.htm',
                            params: {"articleId": data[i]['id']},
                            method: 'JSONP',
                            jsonp: 'jsonp'
                        }).then(function (response){
                            var d = JSON.parse(response.bodyText);
                            if (d.errorCode == 0) {
                                // 处理浏览量
                                data[i]['view'] = d.result;
                                num = num - 1;
                            }
                            if (num == 0) {
                                // 推荐列表
                                me.listMsg = data;
                            }
                        });
                    })(i);
                }
            } 
        },
        
        /**
         * 栏目下拉
         */
        showDetails: function() {
            var me = this;
            var docMain = document.querySelector('.doc-main');
            var detailIcon = document.querySelector('.detail-icon');
            if (me.flog) {
                docMain.style.height = '100%';
                detailIcon.src = require('../../../assets/image/discover/details-icon-top.png')
                me.flog = false;
            } else {
                docMain.style.height = '6.6rem';
                detailIcon.src = require('../../../assets/image/discover/details-icon.png')
                me.flog = true;
            }
        },
        
        /**
         * 是否是空对象
         * @param {Object} obj
         */
        isEmptyObject: function(obj) {
            return JSON.stringify(obj) === '{}' ? false : true;
        },
        
        /**
         * 实体转 HTML
         * @param {String} str 带有 HTML实体的字符串
         * @return {String} str 转换成功HTML
         */
        HTMLDeCode(str) { 
            if (!str || str.length == 0) return '';
            
            str = str.replace(/&amp;/g, '&'); 
            str = str.replace(/&lt;/g, '<');
            str = str.replace(/&gt;/g, '>');
            str = str.replace(/&quot;/g, "''");  
            str = str.replace(/&#039;/g, "'");  
            str = str.replace(/&#32;/g, '&nbsp;');
            return str;
        },
        
        /**
         * html转 实体  
         * @param {Object} str
         */
        htmlDecodeByRegExp: function (str){
            var s = "";
            if(s || str.length == 0) return "";
            return str
              .replace(str ? /&(?!#?\w+;)/g : /&/g, '&amp;')
              .replace(/&lt;/g, "<")
              .replace(/&gt;/g, ">")
              .replace(/&quot;/g, "\"")
              .replace(/&#39;/g, "\'")
              .replace(/&quot;/g,"\"")
              .replace(/&amp;/g,"&")
              .replace(/&nbsp;/g," ")
              .replace(/&#32;/g, ' ');
        },
        
        /**
         * 解析json
         * @param {Object} data
         * @return 
         */
        parseData: function(data) {
            var _data;
            if (!data) return data;
            try{
                _data = JSON.parse(data);
            }catch(e){
                _data = data;
            }
            return _data;
        }
    }  
//  methods end 
}

    
</script>
<style type="text/css">
body {
    background: #f4f4f4;
    margin: 0;
    padding: 0;
}
body * {
    margin: 0;
    padding: 0;
}
.mt10 {
    padding-top: 10px;
    margin-top: 0 !important;
} 
.play-count {
    color: #8392a0;
    float: left;
}
h3,h5 {
    font-weight: normal; 
}

.fl {
    float: left;
}
.fr {
    float: right;
}

#vjs_video_3 .vjs-big-play-button{
    background-color:none;
}

.video-js .vjs-big-play-button{
    height: 2em !important;
    line-height: 2em !important;
    margin-top: -1em !important;
    border-radius: 5rem!important;
    width: 2em!important;
}
.video-js.vjs-custom-skin .vjs-big-play-button{
    background-color: rgba(0,0,0,0.45)!important;
    margin-left: -1em!important;
}
</style>
<style lang="scss" scoped>

@import '../../../assets/css/common.scss';
  
h1,h2,h3,h4,h5 {
    -webkit-margin-before: 0em;
    -webkit-margin-after: 0em;
    -webkit-margin-start: 0px;
    -webkit-margin-end: 0px;
    
}

@function rem($px){
  @return $px / 10 * 1rem;
}  
  
$_fff: #fff;
$_243742: #243742; 

$sans-serif: "PingFangSC-Regular,'Helvetica Neue', Helvetica, Rotobo";
$font-family: $sans-serif;
    
    
$fontSize16:rem(16);
$fontSize14: rem(14);
@mixin ban_line{
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
}
.last-end {
    text-align: center;
    line-height: rem(50);
    font-size: rem(12);
}

.video-details-area {
    font-family: "Microsoft YaHei";
} 

.video-main{
    width:100%;
    /*height:rem(217);*/
    overflow:hidden;
    background:#000;
    font-family: "microsoft yahei";
    .video-box{
        width:100%;
    }
    .video-js{

    }
}


.detail-doc{
    background: #fff;
    padding: rem(20) rem(14) rem(10);
    position:relative;
    .doc-title{
        /*width:rem(180);*/
        width: 100%;
        line-height:rem(30);
        /*font-size:$fontSize16;*/
        font-size:rem(18);
        color:#243742;
        display:block;
        font-weight: normal;
        -webkit-margin-before: 0em;
        -webkit-margin-after: 0em;
        -webkit-margin-start: 0px;
        -webkit-margin-end: 0px;
        /*// @include ban_line;//省略号*/
    }
    .doc-sub{
        /*width:rem(200);*/
        line-height:rem(20);
        /*font-size:$fontSize14;*/
        font-size: rem(16);
        color:#8392a0;
        display:block;
        /*margin-bottom:rem(13);*/
        padding: rem(14) 0 rem(3) 0;
        /*@include ban_line;//省略号*/
        font-style: normal;
    }
    .more-btn{
        width:rem(20);
        height:rem(20);
        display:block;
        position:absolute;
        top: rem(18);
        right:rem(20);
        color: #8392a0;
        font-size: rem(20);
        font-weight: normal;
    }
}
.doc-main{
    height: rem(66);
    overflow:hidden;
    p{
        line-height: 130% !important;
        /*line-height:rem(18);*/
        font-size: rem(14) !important;
        color:#8392a0 !important;
    }
}
.doc-play-msg{
    margin-top:rem(12);
    padding-top:rem(12);
    border-top:1px solid #dedede;
    overflow: hidden;
}
.recommend{
    margin-top: rem(20);
    /*padding:rem(15);*/
}   
.rec {
    background: #fff;
    font-size: rem(16);
    padding-left: rem(10);
    padding-top: rem(10);
    line-height: rem(30);
} 
   
</style>